import { Injectable, Module } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { GoodsType } from 'src/goodsType/goodsType.entity';
import { Sku } from 'src/sku/sku.entity';
import { SkuType } from 'src/skuType/skuType.entity';
import { Repository } from 'typeorm';
import { Goods } from './goods.entity';
@Module({
  imports: [GoodsType, Sku, SkuType]
})
@Injectable()
export class GoodsService {
  constructor(
    @InjectRepository(Goods)
    private goodsRepository: Repository<Goods>,
    @InjectRepository(GoodsType)
    private goodsTypeRepository: Repository<GoodsType>,
    @InjectRepository(Sku)
    private skuRepository: Repository<Sku>,
    @InjectRepository(SkuType)
    private skuTypeRepository: Repository<SkuType>,
  ) { }

  async findAll() {
    // query all goods type 
    const goodsTypeList = await this.goodsTypeRepository.find();
    const result = goodsTypeList.map(item => ({ ...item }))
    for (let item of result) {
      let goodsList = this.goodsRepository
        .createQueryBuilder("goods")
        .where("goods.typeId = :typeId", { typeId: item.id })
        .orderBy("id")
        .getMany()
      item['data'] = (await goodsList).map(item => ({ ...item }))
      for (let item1 of item['data']) {
        // query skuTypeList 
        let skuTypeList = this.skuTypeRepository
          .createQueryBuilder('skuType')
          .where("skuType.goodsId = :goodsId", { goodsId: item1.id })
          .orderBy("id")
          .getMany()
        item1['skuList'] = (await skuTypeList).map(item => ({ ...item, max: item.maximum }))
        for (let item2 of item1['skuList']) {
          // query sku detail list 
          let dataList = this.skuRepository
            .createQueryBuilder('sku')
            .where("sku.skuTypeId = :skuTypeId", { skuTypeId: item2.id })
            .orderBy("id")
            .getMany()
          item2['data'] = (await dataList).map(item => ({...item}))
        }
      }
    }
    return result;
  }

  findOne(id: number): Promise<Goods> {
    return this.goodsRepository.findOne(id);
  }

  async remove(id: number): Promise<void> {
    await this.goodsRepository.delete(id);
  }
  getHello(): string {
    return 'Hello World! Goods Service';
  }
}